package ar.com.binarit

import java.util.List;

import ar.com.binarit.entities.Mubbia
import ar.com.binarit.entities.TipoUsuario;

class Person {

	transient springSecurityService

	String username
	String password
	String email
	boolean enabled
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired
	
	String nickname
	
	TipoUsuario tipoUsuario
	String imgAvatar
	
	int valorRanking
	
	List tagsUtilizados
	
	static hasMany = [
		mubbiasCreadas : Mubbia, mubbiasFavoritas : Mubbia, mubbiasParticipando : Mubbia
	]
	
	static mappedBy = [mubbiasCreadas : "usuarioCreador", mubbiasFavoritas:"usuariosFavoritos", mubbiasParticipando:"usuariosParticipantes"]


	static constraints = {
		username blank: false, unique: true
		password blank: false
		email (email: true, nullable: false)
		tipoUsuario(nullable: false)
		nickname(size:1..100)
		mubbiasFavoritas(nullable: true)
		mubbiasParticipando(nullable: true)
		tagsUtilizados(nullable: true)
		imgAvatar(nullable:true)
		nickname(nullable:true)
		tipoUsuario(nullable: true)
	}

	static mapping = {
		password column: '`password`'
	}

	public Mubbia(){
		tagsUtilizados = new ArrayList()
		tipoUsuario = TipoUsuario.normal()
	}
	
	String toString(){
		"${username}"
	}
	
	def traerDatosRelacionados() {
		tipoUsuario?.descripcion
	}
	
	def unirse(mubbia){
		this.addToMubbiasParticipando(mubbia)
	}
	
	def desunirse(mubbia){
		this.removeFromMubbiasParticipando(mubbia)
	}
	
	public boolean equals(Object otro) {
		try {
			return username?.equalsIgnoreCase(otro?.username)
		} catch (ClassCastException e) {
			return false
		}
	}
	
	public int hashCode() {
		return username.hashCode()
	}
	Set<Role> getAuthorities() {
		PersonRole.findAllByPerson(this).collect { it.role } as Set
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		if (password){
			password = springSecurityService.encodePassword(password)
		}
	}
	
	boolean validarNuevoPerfil(){
		if (!this.email || this.email.equals("")){
			this.errors.rejectValue("email", 'default.null.message',['email']as Object[], "");
		}
		
		if (!this.password || this.password.equals("")){
			this.errors.rejectValue("password", 'default.null.message',['password']as Object[], "");
		}

	}
}
